package ui;

import dao.StudentDao;
import model.Student;

import javax.swing.*;
import java.awt.*;

public class RegisterFrame extends JFrame {

    public RegisterFrame() {
        setTitle("学生注册 - 奖学金系统");
        setSize(450, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JLabel titleLabel = new JLabel("学生注册", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 22));
        titleLabel.setForeground(new Color(220, 20, 100));
        add(titleLabel, BorderLayout.NORTH);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 60, 20, 60));
        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField genderField = new JTextField();
        JTextField gradeField = new JTextField();
        JTextField majorField = new JTextField();
        JPasswordField pwdField = new JPasswordField();

        panel.add(new JLabel("学号："));
        panel.add(idField);
        panel.add(new JLabel("姓名："));
        panel.add(nameField);
        panel.add(new JLabel("性别："));
        panel.add(genderField);
        panel.add(new JLabel("年级："));
        panel.add(gradeField);
        panel.add(new JLabel("专业："));
        panel.add(majorField);
        panel.add(new JLabel("密码："));
        panel.add(pwdField);

        JButton registerBtn = new JButton("注册");
        registerBtn.setBackground(new Color(255, 105, 180));
        registerBtn.setForeground(Color.white);
        registerBtn.setFocusPainted(false);
        panel.add(new JLabel(""));
        panel.add(registerBtn);

        add(panel, BorderLayout.CENTER);

        registerBtn.addActionListener(e -> {
            String id = idField.getText().trim();
            String name = nameField.getText().trim();
            String gender = genderField.getText().trim();
            String grade = gradeField.getText().trim();
            String major = majorField.getText().trim();
            String pwd = new String(pwdField.getPassword()).trim();

            // 检查是否有空字段
            if (id.isEmpty() || name.isEmpty() || gender.isEmpty() || grade.isEmpty()
                    || major.isEmpty() || pwd.isEmpty()) {
                JOptionPane.showMessageDialog(this, "所有字段均为必填，不能有空值", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Student stu = new Student(id, name, gender, grade, major, pwd);
            StudentDao dao = new StudentDao();

            if (dao.addStudent(stu)) {
                JOptionPane.showMessageDialog(this, "注册成功！");
                new LoginFrame();
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "注册失败，学号可能已存在", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        setVisible(true);
    }
}
